package com.data.modules.system.util.crypto;

/**
 *
 * @author: gao
 * @since: 2022-03-16
 **/

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.data.common.exception.BootException;
import com.data.common.util.RestUtil;
import com.data.modules.oss.service.IOSSFileService;
import com.jeecg.dingtalk.api.core.vo.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileUrlResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


/**
 * 飞书审批工具类
 */
@SuppressWarnings("ALL")
@Slf4j
@Component
public class FsCryptUtil {



    @Autowired
    private IOSSFileService ossFileService;

    /**https://www.feishu.cn/approval/openapi/v2/file/upload
     * 飞书上传附件的Url Post
     */
    String uploadUrl = "https://www.feishu.cn/approval/openapi/v2/file/upload";

    /**
     * 飞书审批的Url Post
     */
    String approveUrl = "https://www.feishu.cn/approval/openapi/v2/instance/create";

    /**
     *文件上传给飞书
     * @param contractUrl
     * @return
     */
    public static String uploadFile(String contractUrl){


        return  null;
    }



    public String sendApprove (){

        return  null;
    }


    /**
     * 上传文件到飞书获取返回的文件code唯一码
     * 且附件上传大小限制为50M，图片上传大小为10M。
     * @param fileUrl
     * @return
     */
    public static final String flyBookUpload(String fileUrl) {
        String type = "file";
        String accessToken = getAccessToken();
        if (accessToken != null) {
            accessToken = "Bearer " + accessToken;
        }
        RestTemplate restTemplate = null;
        URI uri = null;
        HttpEntity<MultiValueMap<String, Object>> requestEntity = null;
        try {
            restTemplate = new RestTemplate();
            String getapprovaldetail = "https://www.feishu.cn/approval/openapi/v2/file/upload";
            uri = UriComponentsBuilder.fromHttpUrl(getapprovaldetail).build().toUri();

            URL uriFile = new URL(fileUrl);
            FileUrlResource fileUrlResource = new FileUrlResource(uriFile);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            ContentDisposition build = ContentDisposition.builder("form-data").filename(fileUrlResource.getFilename()).build();
            headers.setContentDisposition(build);
            headers.set("Authorization",accessToken);
            MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
            params.add("content", fileUrlResource);
            params.add("name", "框架协议-3月华南深圳市禾升信息.xlsx");
            params.add("type", "attachment");
            requestEntity = new HttpEntity<>(params, headers);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = restTemplate.postForObject(uri, requestEntity, JSONObject.class);
        if (ObjectUtils.isEmpty(jsonObject) || jsonObject.getInteger("code") != 0) {
            throw new BootException("上传临时素材失败" + jsonObject.toJSONString());
        }
        log.info("[mediaUpload]", "mediaUpload response:{}", new Object[]{jsonObject});
        JSONObject jsonObjectData = (JSONObject) JSONObject.toJSON(jsonObject.get("data"));
        return String.valueOf(jsonObjectData.get("code"));
    }


    public static void main(String[] args) throws IOException {

        test();
        System.out.println(123123);
    }

    public static JSONObject postRequest(String strUrl, Map<String, Object> params, HttpHeaders headers) {
        JSONObject response = RestUtil.request(strUrl, HttpMethod.POST, headers, null, JSON.toJSON(params), JSONObject.class).getBody();
        return response;
    }

    public static JSONObject postRequest(String strUrl, String  params, HttpHeaders headers) {
        JSONObject response = RestUtil.request(strUrl, HttpMethod.POST, headers, null, JSON.toJSON(params), JSONObject.class).getBody();
        return response;
    }

    public static void test(){
        String approveUrl = "https://www.feishu.cn/approval/openapi/v2/instance/create";
        String accessToken = getAccessToken();
        if (accessToken != null) {
            accessToken = "Bearer " + accessToken;
        }
        String jsonObjct = "{\r\n \"approval_code\":\"60A0D11A-F8F5-41A7-AB88-539EB0831DE4\",\r\n    \"user_id\":\"42d91484\",\r\n    \"open_id\":\"42d91484\",\r\n    \"form\":\"[{\\\"id\\\":\\\"widget16474168248790001\\\",\\\"name\\\":\\\"提交时间\\\",\\\"type\\\":\\\"date\\\",\\\"value\\\":\\\"2019-10-01T08:12:01+08:00\\\"},{\\\"id\\\":\\\"widget15995460603370001\\\",\\\"name\\\":\\\"合同名称\\\",\\\"type\\\":\\\"input\\\",\\\"value\\\":\\\"test\\\"},{\\\"id\\\":\\\"widget16474169027270001\\\",\\\"name\\\":\\\"合同起始日\\\",\\\"type\\\":\\\"date\\\", \\\"value\\\":\\\"2019-10-01T08:12:01+08:00\\\"},{\\\"id\\\":\\\"widget16474169049770001\\\",\\\"name\\\":\\\"合同终止日\\\",\\\"type\\\":\\\"date\\\", \\\"value\\\":\\\"2019-10-01T08:12:01+08:00\\\"},{\\\"id\\\":\\\"widget16474169283220001\\\",\\\"name\\\":\\\"合作商\\\",\\\"type\\\":\\\"input\\\", \\\"value\\\":\\\"test\\\"},{\\\"id\\\":\\\"widget16474169397660001\\\",\\\"name\\\":\\\"合同类型\\\",\\\"type\\\":\\\"input\\\", \\\"value\\\":\\\"test\\\"},{\\\"id\\\":\\\"widget16474169568600001\\\",\\\"name\\\":\\\"备注\\\",\\\"type\\\":\\\"input\\\", \\\"value\\\":\\\"test\\\"},{\\\"id\\\":\\\"widget15995462559070001\\\",\\\"name\\\":\\\"合同附件\\\",\\\"type\\\":\\\"attachmentV2\\\", \\\"value\\\":[\\\"07D32BBC-6527-442D-A30E-3A7A5317869E\\\"]}]\"\r\n}";
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization",accessToken);
        headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
        JSONObject jsonObject = postRequest(approveUrl, jsonObjct, headers);
        System.out.println("qweq");
    }

    public static String getAccessToken() {
        String appId = "cli_a2a5be63077bd00b";
        String appSecret = "mbc3Lapjbet7uafLM3ZnMf6K2UxydJ0B";
        AccessToken accessToken = null;
        String strUrl = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
        HashMap<String, String> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("app_secret", appSecret);
        JSONObject response = RestUtil.request(strUrl, HttpMethod.POST, headers, null, JSON.toJSON(params), JSONObject.class).getBody();
        /**
         * 请求飞书成功 返回 errcode 对应的是 token生效时间
         * 请求飞书失败 返回 errcode 对应的是 服务端错误码
         *
         * https://open.feishu.cn/document/ukTMukTMukTM/ugjM14COyUjL4ITN 找相应错误码解决问题
         *
         * */
        int errcode;
        if (response != null && ObjectUtil.equal(response.get("code"), 0)) {
            String access_token = response.getString("app_access_token");
            errcode = response.getIntValue("expire");
            accessToken = new AccessToken(access_token, errcode);
            log.info("[ACCESS_TOKEN] 获取ACCESS_TOKEN成功:{}", accessToken);
        } else {
            errcode = response.getIntValue("code");
            String errmsg = response.getString("errmsg");
            log.info("[ACCESS_TOKEN] 获取ACCESS_TOKEN失败 errcode:{} errmsg:{}", errcode, errmsg);
        }
        if (accessToken != null) {
            return accessToken.getAccessToken();
        }
        log.warn("获取AccessToken失败");
        return null;
    }

}

